package com.zheng.shop.rpc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.mapper.ShopSkuMapper;
import com.zheng.shop.dao.model.ShopSku;
import com.zheng.shop.rpc.api.ShopSkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zheng.shop.common.Enum.ProductStatusType;
import com.zheng.shop.dao.model.*;
import com.zheng.shop.rpc.api.ShopSkuAttributeService;
import com.zheng.shop.rpc.api.ShopSkuDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author likun
 * @since 2017-12-29
 */
@Service
@Transactional(rollbackFor = ShopException.class)
@BaseService
public class ShopSkuServiceImpl extends BaseServiceImpl<ShopSkuMapper, ShopSku> implements ShopSkuService {

    @Autowired
    private ShopSkuMapper shopSkuMapper;
    @Autowired
    private ShopSkuAttributeService skuAttributeService;
    @Autowired
    private ShopSkuDetailService skuDetailService;

    @Override
    public boolean createSku(ShopSku sku) {
        sku.setCtime(new Date());
        sku.setFreezeInventory(0);
        sku.setSales(0);
        return insert(sku);
    }

    @Override
    public int createSkuList(List<ShopSku> skuList) throws ShopException {
        for (int i = 0; i < skuList.size(); i++) {
            if (!createSku(skuList.get(i))) {
                throw new ShopException("添加sku失败！");
            }
        }
        return skuList.size();
    }

    @Override
    public boolean createSku(JSONObject skuJson, ShopProduct product) throws ShopException {
        ShopSku sku = skuJson.toJavaObject(ShopSku.class);
        sku.setId(null);
        sku.setCostPrice(sku.getCostPrice().setScale(2));
        sku.setPrice(sku.getPrice().setScale(2));
        sku.setMarketPrice(sku.getMarketPrice().setScale(2));
        sku.setStatus(ProductStatusType.NORMAL.key);
        sku.setBrandId(product.getBrandId());
        sku.setMarketable(product.getMarketable());
        sku.setProductCategoryId(product.getProductCategoryId());
        sku.setProductId(product.getId());
        sku.setCtime(new Date());
        sku.setFreezeInventory(0);
        sku.setSales(0);
        insert(sku);

        ShopSkuDetail skuDetail = new ShopSkuDetail();
        skuDetail.setSkuId(sku.getId());
        //todo 添加sn
//        skuDetail.setSkuSn();
        skuDetail.setWeight(skuJson.getBigDecimal("weight"));
        skuDetailService.insert(skuDetail);
        //sku 属性
        JSONArray attributeArray = skuJson.getJSONArray("attribute");
        if (null == attributeArray) {
            return true;
        }
        //添加关联
        List<Integer> skuAttributeIdList = new ArrayList<>();
        for (int i = 0; i < attributeArray.size(); i++) {
            JSONObject attributeJson = attributeArray.getJSONObject(i);
            ShopSkuAttribute skuAttribute = attributeJson.toJavaObject(ShopSkuAttribute.class);
            skuAttribute.setSkuId(sku.getId());
            Boolean hasImage = attributeJson.getBoolean("hasImage");
            if (!hasImage) {
                skuAttribute.setImage(null);
            }
            if (!skuAttributeService.insert(skuAttribute)) {
                throw new ShopException("新增sku属性失败！");
            }
            skuAttributeIdList.add(skuAttribute.getId());
        }
        if (skuAttributeIdList.size() < 1) {
            skuAttributeIdList = null;
        }
        sku.setSkuAttributeIds(JSONObject.toJSONString(skuAttributeIdList));
        if (!updateById(sku)) {
            throw new ShopException("新增sku失败！");
        }
        return true;
    }

    @Override
    public int createSkuList(JSONObject param, ShopProduct product) throws ShopException {
        JSONArray skuArray = param.getJSONArray("skus");
        //获取到添加的属性集合
        for (int i = 0; i < skuArray.size(); i++) {
            JSONObject skuJSON = skuArray.getJSONObject(i);
            if (!createSku(skuJSON, product)) {
                throw new ShopException("新增sku失败！");
            }
        }
        return skuArray.size();
    }

    @Override
    public boolean updateSku(ShopSku sku) throws ShopException {
        return false;
    }

    public boolean updateSku(JSONObject skuJson, ShopProduct product, JSONArray existSkuArray) throws ShopException {
        //找到所有已有的sku，并对比编辑的sku，如果有完全一致的规格，就修改该sku，如果没有，就添加该sku；
        //并为所有修改的sku添加flag
        //然后将未设置flag的sku设置为已删除
        boolean updateFlag = false;
        JSONArray attributeJsonArray = skuJson.getJSONArray("attribute");
        if (null != attributeJsonArray) {
            List<ShopSkuAttribute> skuAttributeList = attributeJsonArray.toJavaList(ShopSkuAttribute.class);
            int skuAttributeListSize = skuAttributeList.size();
            for (int i = 0; i < existSkuArray.size(); i++) {
                JSONObject existSkuJson = existSkuArray.getJSONObject(i);
                Integer existSkuId = existSkuJson.getInteger("id");
                EntityWrapper<ShopSkuAttribute> skuAttributeEntityWrapper = new EntityWrapper<>();
                skuAttributeEntityWrapper.where("sku_id=" + existSkuId);
                List<ShopSkuAttribute> existSkuAttributeList = skuAttributeService.selectList(skuAttributeEntityWrapper);
                int existSkuAttributeListSize = existSkuAttributeList.size();
                //如果两个长度对不上，就不需要判断，直接添加
                if (skuAttributeListSize != existSkuAttributeListSize) {
                    updateFlag = false;
                    continue;
                }
                //判断是否完全一致
                int sameNum = 0;
                for (int j = 0; j < existSkuAttributeListSize; j++) {
                    ShopSkuAttribute existSkuAttribute = existSkuAttributeList.get(j);
                    Integer existAttributeKeyId = existSkuAttribute.getAttributeKeyId();
                    String existAttributeValue = existSkuAttribute.getAttributeValue();
                    for (int k = 0; k < skuAttributeListSize; k++) {
                        ShopSkuAttribute skuAttribute = skuAttributeList.get(k);
                        Integer attributeKeyId = skuAttribute.getAttributeKeyId();
                        String attributeValue = skuAttribute.getAttributeValue();
                        if (existAttributeKeyId.equals(attributeKeyId) && existAttributeValue.equals(attributeValue)) {
                            sameNum++;
                        }
                    }
                    //如果匹配的个数一致，就修改该sku
                    if (sameNum == skuAttributeListSize) {
                        updateFlag = true;
                        existSkuJson.put("updateFlag", true);
                        skuJson.put("id", existSkuId);
                        break;
                    }
                }
                if (updateFlag) {
                    //如果已有匹配的sku，就跳出循环吧
                    break;
                }
            }
        } else {
            //没有规格的就找到对应的唯一sku添加flag
            for (int i = 0; i < existSkuArray.size(); i++) {
                JSONObject existSkuJson = existSkuArray.getJSONObject(i);
                if (existSkuJson.getInteger("id").equals(skuJson.getInteger("id")) || existSkuJson.getString("sku_attribute_ids") == null) {
                    existSkuJson.put("updateFlag", true);
                }
            }
            updateFlag = true;
        }
        if (updateFlag) {
            //修改
            ShopSku sku = skuJson.toJavaObject(ShopSku.class);
            if (null == sku.getId()) {
                EntityWrapper<ShopSku> skuEntityWrapper = new EntityWrapper<>();
                skuEntityWrapper.where("product_id=" + product.getId()).isNotNull("sku_attribute_ids");

                ShopSku existSku = selectOne(skuEntityWrapper);
                if (existSku == null) {
                    createSku(skuJson, product);
                    return true;
                }
                sku.setId(existSku.getId());
            }
            sku.setMtime(new Date());
            sku.setStatus(ProductStatusType.NORMAL.key);
            sku.setMarketable(product.getMarketable());
            EntityWrapper<ShopSkuAttribute> skuAttributeEntityWrapper = new EntityWrapper<>();
            skuAttributeEntityWrapper.where("sku_id=" + sku.getId());
            List<ShopSkuAttribute> updateSkuAttributeList = skuAttributeService.selectList(skuAttributeEntityWrapper);
            if (updateSkuAttributeList.size() > 0) {
                for (int i = 0; i < attributeJsonArray.size(); i++) {
                    JSONObject attributeJson = attributeJsonArray.getJSONObject(i);
                    Integer attributeKeyId = attributeJson.getInteger("attributeKeyId");
                    String attributeValue = attributeJson.getString("attributeValue");
                    Boolean hasImage = attributeJson.getBoolean("hasImage");
                    if (hasImage) {
                        for (ShopSkuAttribute skuAttribute : updateSkuAttributeList) {
                            if (attributeKeyId.equals(skuAttribute.getAttributeKeyId()) && attributeValue.equals(skuAttribute.getAttributeValue())) {
                                skuAttribute.setImage(attributeJson.getString("image"));
                                skuAttributeService.updateById(skuAttribute);
                            }
                        }
                    }
                }
            }
            EntityWrapper<ShopSkuDetail> skuDetailEntityWrapper = new EntityWrapper<>();
            skuDetailEntityWrapper.where("sku_id=" + sku.getId());

            ShopSkuDetail skuDetail = skuDetailService.selectOne(skuDetailEntityWrapper);
            skuDetail.setWeight(skuJson.getBigDecimal("weight"));
            skuDetailService.updateById(skuDetail);
            if (!updateById(sku)) {
                throw new ShopException("修改sku失败！");
            }
        } else {
            //添加
            createSku(skuJson, product);
        }
        return true;
    }

    @Override
    public int updateSkuList(JSONObject param, ShopProduct product) throws ShopException {
        JSONArray skuArray = param.getJSONArray("skus");
        //获取已经存在的sku集合
        List<Map<String, Object>> skuMapList = selectSkuMapList(product.getId(), ProductStatusType.NORMAL.key);
        skuMapList.addAll(selectSkuMapList(product.getId(), ProductStatusType.DELETED.key));
        skuMapList.addAll(selectSkuMapList(product.getId(), ProductStatusType.FREEZE.key));
        JSONArray existSkuArray = JSONArray.parseArray(JSON.toJSONString(skuMapList));
        for (int i = 0; i < skuArray.size(); i++) {
            JSONObject skuJSON = skuArray.getJSONObject(i);
            if (!updateSku(skuJSON, product, existSkuArray)) {
                throw new ShopException("修改sku失败！");
            }
        }
        for (int i = 0; i < existSkuArray.size(); i++) {
            Boolean updateFlag = existSkuArray.getJSONObject(i).getBoolean("updateFlag");
            if (null == updateFlag || !updateFlag) {
                Integer id = existSkuArray.getJSONObject(i).getInteger("id");
                ShopSku shopSku = selectById(id);
                shopSku.setMarketable(false);
                shopSku.setStatus(ProductStatusType.DELETED.key);
                updateById(shopSku);
            }
        }
        return skuArray.size();
    }

    @Override
    public boolean deleteSkuList(List<Integer> idList) throws ShopException {
        return false;
    }

    @Override
    public List<Map<String, Object>> selectSkuAttributeList(Integer skuId) {
        return shopSkuMapper.selectSkuAttributes(skuId);
    }

    @Override
    public List<Map<String, Object>> selectSkuMapList(Integer productId, Integer status) {
        return shopSkuMapper.selectSkuMapList(productId, status);
    }
}
